import { program } from 'commander';
import {build,serve,preview} from './vite';

import commit from './commit';
import deploy from './deploy/index-v2';
import extractNpmRely from './extractNpmRely';
import init from './new-init';
import { proxy } from './proxy';
import initSpec from './spec';
import upload from './upload';
import { getPkg } from './utils';

export const run = () => {
  const pkg = getPkg();
  program.version(pkg?.version, '-V, --version', '查看版本');

  // program
  //   .command('init [initName]')
  //   .description('初始化项目')
  //   .option('-u, --umi <name>', 'create Umijs')
  //   .option('-v, --viteAntd <name>', 'create Vite + antd')
  //   .action(function (name, option) {
  //     if (option) {
  //       init(name || option);
  //     }
  //   });

  program
    .command('init')
    .description('模板选择,也可通过qps -tpl/--template templateName快速创建')
    .option('-tpl, --template <templateName>', '模板名称')
    .action(function (cmd) {
      init(cmd?.template);
    });

  program
    .command('spec')
    .description('生成eslint、stylelint、commitlint相关配置文件')
    .action(async function () {
      initSpec();
    });

  program
    .command('cm')
    .option('-b, --branch')
    .description('add commit rebase 指令集成')
    .action(async function () {
      commit();
    });

  program
    .command('extractNpmRely')
    .description('抽离三方依赖为CDN的方式')
    .action(async function () {
      extractNpmRely();
    });

  program
    .command('deploy [env]')
    .option('-b, --branch <branchName>', '分支名称')
    .option('-n, --name <name>', '项目名')
    .option('-log, --log', '打印发布信息')
    .description('自动化发布, 示例: qps deploy 分支名换 环境 项目名称')
    .action(async function (name, option) {
      try {
        await deploy(name, option);
      } catch (err) {
        console.log(err.toString());
      }
    });
  program
    .command('upload [path]')
    // .option('-p, --file [path]', '文件地址')
    .option('-f, --file <path>', '文件地址')
    .description('文件上传, 示例: qps upload [path] -f [file]')
    .action(async function (name, option) {
      try {
        await upload(name, option?.file);
      } catch (err) {
        console.log(err.toString());
      }
    });

  program
    .command('build')
    .description('qps build')
    .action(async function () {
      await build();
    });

  program
    .command('serve')
    .description('qps serve')
    .action(async function () {
      await serve();
    });

  program
    .command('preview')
    .description('qps preview')
    .action(async function () {
      await preview();
    });

  program
    .command('proxy [mode]')
    .option('-r, --shadowRules <rules>', '设置匹配规则')
    .option('-p, --proxy <proxy>', '设置代理端口')
    .description(
      '本地代理[mode]：start后台、 run前台启动、stop停止代理服务、restart、off关闭代理、init初始化',
    )
    .action(async function (name, option) {
      proxy({
        type: name,
        shadowRules: option?.shadowRules,
        proxy: option?.proxy,
      });
    });
  program.parse(process.argv);
};
